// pages/near/near.js
var fileData = require('../../utils/data.js');
var main = require('../../utils/main.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showSelect: false,
    navTopItems: '',
    submitData: {
      loginUserId: '', //	登录用户id	
      myLongitude: '', //	登录用户经度	
      myLatitude: '', //	登录用户纬度
      orderCondition: '', //	排序方式0：根据距离 1：根据人气 2：根据评价
      industry: '', //	行业类别	
      currentPage: 1, //	当前页码	
      pageNumber: 10, //	每页显示条数	
      param: '',
      miles: '5000' //	附近多少米	
    },
    location:'',
    streetName:'',
    hasData: true,
    advertImg_url: '',
    bottabData: app.globalData.bottabDataForPpsj,
    isShop: '',
    isPerson: false,
    advert_url: '',
    shopInfo: [],
    isIndex: '',
    indexname0: '全部分类',
    indexname1: '智能排序',
    selectKey:'',
    allTypes: [{ id: '', title: '全部分类' }, { id: 1, title: '美食' }, { id: 2, title: '酒店' }, { id: 3, title: '休闲娱乐' }, { id: 4, title: '丽人美发' }, { id: 5, title: '宠物' }, { id: 6, title: '母婴' }, { id: 7, title: '结婚摄影' }, { id: 8, title: '运动健身' }, { id: 9, title: '汽车服务' }, { id: 10, title: '家装建材' }, { id: 11, title: '教育培训' }, { id: 12, title: '服装鞋帽' }, { id: 13, title: '货运搬家' }, { id: 14, title: '家政' }, { id: 15, title: '更多' }],
    isFocus: false,
    loadSuccess: false
  },
  onSlideChangeEnd: function (e) {
    var that = this;
    that.setData({
      current: e.detail.current + 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    if(wx.getStorageSync('location')){
      this.setData({
        location: wx.getStorageSync('location'),
        ['bottabData[1].current']: true,
        userInfo: JSON.parse(wx.getStorageSync('userInfo')),
        ['submitData.loginUserId']: JSON.parse(wx.getStorageSync('userInfo')).id,
        ['submitData.myLongitude']: wx.getStorageSync('location').longitude,
        ['submitData.myLatitude']: wx.getStorageSync('location').latitude,
      })
      fileData.getAdvertData.apply(this, ['4', 'advert_url']);
      this.getBannerData('4', 'top', 1, 'advertImg_url');
      this.getShopInfo();
    }
  },
  enterDesk: function () {
    wx.navigateTo({
      url: '/pages/infoDesk/infoDesk?index=4',
    })
  },
  // 打开地图
  openMap: function(){
    wx.navigateTo({
      url: '/pages/nearmap/nearmap',
    })
  },
  // 展示隐藏下拉框
  hideSelect: function(){
    this.setData({
      showSelect: false
    })
  },
  focusFunc: function(){
    this.setData({
      isFocus: true
    })
  },
  blurFunc: function(e){
    if(!e.detail.value){
      this.setData({
        isFocus: false
      })
    }
  },
  inputFunc: function(e){
    this.setData({
      ['submitData.param']: e.detail.value,
      ['submitData.currentPage']: 1,
      shopInfo: [],
      hasData: true
    })
    if (!this.data.isPerson) {
      this.getShopInfo()  
    }
    else {
      this.getPersonInfo()
    }

  },
  toggleSelect: function (e) {
    var index= e.currentTarget.dataset.index;
    var key = e.currentTarget.dataset.key;
    if(index == 1){
      var arr = [{ id: '', title: '智能排序' }, { id: 0, title: '离我最近' }, { id: 1, title: '人气最高' }, { id: 2, title: '评价最好' }];
    }
    else{
      var arr = [{ id: '', title: '全部分类' }, { id: 1, title: '美食' }, { id: 2, title: '酒店' }, { id: 3, title: '休闲娱乐' }, { id: 4, title: '丽人美发' }, { id: 5, title: '宠物' }, { id: 6, title: '母婴' }, { id: 7, title: '结婚摄影' }, { id: 8, title: '运动健身' }, { id: 9, title: '汽车服务' }, { id: 10, title: '家装建材' }, { id: 11, title: '教育培训' }, { id: 12, title: '服装鞋帽' }, { id: 13, title: '货运搬家' }, { id: 14, title: '家政' }, { id: 15, title: '更多' }]
    }
    if (index != this.data.isIndex && this.data.showSelect){
      this.setData({
        showSelect: true
      })
    }
    else{
      this.setData({
        showSelect: !this.data.showSelect
      })
    }
    this.setData({
      isIndex: index,
      selectKey: key,
      navTopItems: arr
    })
  },
  selectLabel: function(e){
    var item = e.currentTarget.dataset.item;
    var key = this.data.selectKey;
    var index = this.data.isIndex;
    this.setData({
      [key]: item.title,
      ['submitData.currentPage']: 1,
      ['indexname'+index]: item.title,
      hasData: true,
      shopInfo: [],
      ['submitData.'+key]: item.id,
      showSelect: false
    })
    if (!this.data.isPerson) {
      this.getShopInfo()
    }
    else {
      this.getPersonInfo()
    }
  },
  getIsShop: function () {
    var id = JSON.parse(wx.getStorageSync('userInfo')).id;
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopInfo/getOne',
      data: {
        userId: id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        
        if (!res.data.success) {
          wx.setStorageSync('isShop', '0');
          wx.removeStorageSync('ShopId');
        }
        else {
          wx.setStorageSync('isOut', res.data.data.dateFlag);
          if (res.data.data.data.status == 1) {
            wx.setStorageSync('isShop', '2');
          }
          else {
            wx.setStorageSync('isShop', '1');
            wx.setStorageSync('ShopId', res.data.data.data.id);
          }
        }
        _this.setData({
          isShop: wx.getStorageSync("isShop")
        })
      }
    })
  },
  getBannerData: function (block, position, type, key) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyImg/getImgsByParams',
      data: {
        block: block,
        position: position,
        type: type
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            [key]: res.data.data
          })
        }
      }
    })
  },
  
  // 店铺列表
  getShopInfo: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'nearbyInfo/getShopByPage',
      data: _this.data.submitData,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.success) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
          for (var i = 0; i < res.data.data.pp.length; i++) {
            res.data.data.pp[i].adress = res.data.data.pp[i].adress.split("区")[1];
            res.data.data.pp[i].distance = res.data.data.pp[i].distance.split(".")[0];
            _this.data.shopInfo.push(res.data.data.pp[i])
          }
          _this.setData({
            loadSuccess: true,
            streetName: res.data.data.myPosition,
            shopInfo: _this.data.shopInfo
          })
          if (_this.data.shopInfo.length == res.data.data.page.totalNumber) {
            _this.setData({
              hasData: false
            })
          }
        }
      }
    })
  },

  // 人列表
  getPersonInfo: function () {
    var _this = this;
    var item = _this.data.submitData;
    wx.request({
      url: app.globalData.httpApiCar + 'nearbyInfo/getUserByPage',
      data: { loginUserId: item.loginUserId, myLongitude: item.myLongitude, myLatitude: item.myLatitude, param: item.param, currentPage: item.currentPage, pageNumber: '10',miles:5000},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
          for (var i = 0; i < res.data.data.pp.length; i++) {
            res.data.data.pp[i].distance = res.data.data.pp[i].distance.split(".")[0];
            _this.data.shopInfo.push(res.data.data.pp[i])
          }
          _this.setData({
            shopInfo: _this.data.shopInfo
          })
          if (_this.data.shopInfo.length == res.data.data.page.totalNumber) {
            _this.setData({
              hasData: false
            })
          }
        }
      }
    })
  },
  
  intervalChange: function (e) {
    this.data.navTopdotItems.forEach(function (ele) {
      ele.current = false;
    })
    this.data.navTopdotItems[e.detail.current].current = true;
    this.setData({
      navTopdotItems: this.data.navTopdotItems
    })

  },
  switchBotab(e) {
    let isShop = wx.getStorageSync("isShop");
    let isOut = wx.getStorageSync("isOut"); 
    if (isShop == 1 && e.currentTarget.dataset.value == '入驻') {
      if (isOut == 1) {
        wx.showModal({
          title: '提示',
          content: '您的店铺已到期，请续费',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/shopIndex/shopIndex?whole=1'
              })
            }
          }
        })
      }
      else {
        wx.navigateTo({
          url: '/pages/sjwppublish/sjwppublish'
        })
      }
    }
    else if (isShop == 2 && e.currentTarget.dataset.value == '入驻') { }
    else {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },
  // 打开商家页面
  openIndex(e) {
    var item = e.currentTarget.dataset.item;
    if(!this.data.isPerson){
      wx.navigateTo({
        url: "/pages/shopIndex/shopIndex?id=" + item.id
      })
    }
    else{
      wx.navigateTo({
        url: '/pages/personalProfile/personalProfile?id=' + item.userId
      })
    }
  },
  tabSwitch: function (e) {//tab页面切换
    var isPerson = e.target.dataset.value == "true" ? false : true;
    this.setData({
      isPerson: isPerson,
      ['submitData.currentPage']: 1,
      shopInfo: [],
      hasData: true
    })
    if(this.data.isPerson){
      this.getPersonInfo()
    }
    else{
      this.getShopInfo()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
            success: function (res) {
              if (res.cancel) {
                wx.navigateBack()

              } else if (res.confirm) {
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      //再次授权，调用getLocationt的API
                      wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                          wx.setStorageSync('location', res);
                          that.onLoad()
                        },
                        fail: function (res) {
                          wx.navigateBack()
                        }
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                      wx.navigateBack()
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getIsShop();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.setData({
      ['submitData.currentPage']: 1,
      shopInfo: [],
      hasData: true
    })
    if (this.data.isPerson) {
      this.getPersonInfo()
    }
    else {
      this.getShopInfo()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.hasData) {
      this.setData({
        ['submitData.currentPage']: this.data.submitData.currentPage + 1
      })
      if (this.data.isPerson) {
        this.getPersonInfo()
      }
      else {
        this.getShopInfo()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})